<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

class RbacMiddleware
{
    /**
     * Handle an incoming request.
     * Validate permission to edit this book
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $route = Route::current();
        $uri = $route->uri();
        $middlewares = $route->controllerMiddleware();
        if( in_array('auth',$middlewares)){
            $resources=session('resources');
            if($resources and !$resources->contains($uri)){
                if(stripos($uri,'api')){
                    return response()->json(['msg'=>'authentication failure']);
                }else{
                    abort(404);
                }                
            }
        }
        return $next($request);
    }
}
